package Day24;

import java.io.*;
import java.util.ArrayList;
import java.util.Random;

public class DaoExpress {
    private File file = new File("C:\\Users\\刘娟\\Desktop\\a.txt");
    private ArrayList<Express> list = readFile();
    private Random r = new Random();

    //序列化获取
    public ArrayList<Express> readFile() {
        try (FileInputStream fis = new FileInputStream(file)) {
            ObjectInputStream ois = new ObjectInputStream(fis);
            list = (ArrayList<Express>) ois.readObject();
            ois.close();
        } catch (IOException | ClassNotFoundException e) {
           list = new ArrayList<Express>();
        }
        return list;
    }


    //序列化存储
    public void writeToFile() throws IOException {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
        oos.writeObject(list);
        oos.close();
    }

    //快递添加
    public boolean add(Express e) {
        if (list.size() > 100) {
            return false;
        }
        e.setCode(code());
        e.setGui(gui());
        list.add(e);
        return true;
    }

    //随机生成快递柜
    public int gui() {
        int a = r.nextInt(90) + 10;
        for (Express e : list) {
            if (a == e.getGui()) {
                return gui();
            }
        }
        return a;
    }

    //随机生成取件码
    public int code() {
        int a = r.nextInt(900000) + 100000;
        if (findCode(a) == null) {
            return a;
        }
        return code();
    }

    //查询快递单号
    public Express findByNumber(String number) {
        for (Express e : list) {
            if (number.equals(e.getNumber())) {
                return e;
            }
        }
        return null;
    }

    //根据取件码查询快递
    public Express findCode(int code) {
        for (Express e : list) {
            if (code == e.getCode()) {
                return e;
            }
        }
        return null;
    }

    //删除快递
    public boolean delete(String number) {
        Express e = findByNumber(number);
        if (e == null) {
            return false;
        }
        list.remove(e);
        return true;
    }

    //遍历快递
    public ArrayList<Express> printAll() {
        list = readFile();
        return list;
    }

    //修改快递
    public boolean revise(Express newExpress) {
        if(delete(new View().delete()) == true) {
            return add(newExpress);
        }
        return false;
    }
}
